<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Articles Manager
 * @author	Tran Van Thanh
 * @mail	thanhtran@vietnambiz.com
 * @date	06.09.2011
 */
require_once('admin'.EXT);

class Articles extends Admin {

	function __construct()
	{
		parent::__construct();
		$this->load->model(array('articles_model','cat_articles_model'));
		$this->load->helper(array('upload','text'));			
	}

	function index()
	{
		$page = (isset($_GET['p']) && is_numeric($_GET['p'])) ? $_GET['p'] : 1;
		$this->db->where('type',0);
        if(isset($_GET['status'])) {
            $status = ($_GET['status'] == 'active') ? 'yes' : 'no';
            $this->db->where('status', $status);
        }		
		if(isset($_GET['keyword'])) {    
			$keyword = $_GET['keyword'];
			$keyword = strip_tags($keyword);
			if($keyword == 'keyword')
			{
				$keyword = "";
			}
			else
			{
				$this->db->like('title', $keyword)
            		 ->or_like('description', $keyword)
            		 ->or_like('contents', $keyword)
            		 ->or_like('author', $keyword)
            		 ->or_like('source', $keyword);
			}
        }

		$this->data['articles'] 	= $this->articles_model->get_articles($page != "" ? $page : 1);
		$this->data['page'] 		= $page;

    	$conf =	array(
    		'base_url'		=> admin_url($this->router->class).'/',
    		'total_rows'	=> $this->articles_model->count_all(),
    		'per_page'		=> $this->config->item('articles', 'limit'),
    		'cur_page'		=> $page,
    	);
    	$this->pagination->initialize($conf);
    	$this->data['pagnav'] = $this->pagination->display_query_string();

		if($this->input->is_ajax_request()) {
			$this->load->view('articles/list', $this->data);
		}
		else {
			$this->data['tpl_file']	= 'articles/index';
			$this->load->view('layout/default', $this->data);
		}
	}
	
	function update($id = null)
	{
		$form_submit	=	array();
		$article	=	array();
		$cats	=	$this->cat_articles_model->get_many_by(array('type' => 0));
		if($id)
		{
			$article	=	$this->articles_model->get_by('id',$id);
			$form_submit	=	array(
									'title' => $article->title,
									'desc'	=>	$article->desc,
									'content' => $article->content,
									'hot' => $article->hot,
									'cat_id' => $article->cat_id,
									'active' => $article->active
								);
		}
		
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			$this->form_validation->set_message('required', '%s không hợp lệ!');
    		$this->form_validation->set_rules('txt_title', 'Tiêu đề', 'required|trim|xss_clean');
    		$this->form_validation->set_rules('txt_desc', 'Mô tả', 'required|trim|xss_clean');
    		$title	=	$this->input->post('txt_title');//ascii_link
    		$title_link	=	ascii_link($title);
    		$hot	=	($this->input->post('host') == 1 ? 1 : 0);
    		$active	=	($this->input->post('active') == 1 ? 1 : 0);
    		$cat_id	=	$this->input->post('cat');
    		
    		$data	=	array(
            	'title'	=>	$title,
            	'title_link'	=>	$title_link,
            	'desc'	=>	$this->input->post('txt_desc'),
            	'content'	=>	$this->input->post('txt_content'),
            	'hot'	=>	$hot,
            	'active'	=>	$active,
            	'cat_id'	=>	$cat_id
            );
            
            $form_submit	=	$data;
            
            //if case select image
			if(isset($_FILES["image"]["name"]) && $_FILES["image"]["name"] != '') 
            {
            	// Upload images
            	$album_dir = get_dir_name('news');
            	if(!is_dir($album_dir))
            	{            			
            		create_dir($album_dir);	
            	}
            	
                $ext = get_ext($_FILES["image"]["name"]);
                    if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
                    continue;
                    }
                   
            	if($_FILES['image']['error'] === 0) 
                {            	    	
			        $new_path = $album_dir.$_FILES["image"]["name"];
			        move_uploaded_file($_FILES["image"]['tmp_name'], dirname($_SERVER['SCRIPT_FILENAME']).'/'.$new_path);   			            	    
            		$data['image']	=	$this->_create_thumb($new_path);
                }
                            	        	
            }//End select image
			
			$suc = false;
			//if have article then update with id
			if($article)
			{
				$data['time_update']	=	time();
				if($this->articles_model->update($article->id,$data))
				{
					$suc = true;
				}
			}//end update by id
			else 
			{
				$data['time_create']	=	time();
				if($this->articles_model->insert($data))
				{
					$suc = true;
				}
			}//end add new record
			
			//if success then redirect to list
			if($suc)
			{
				redirect(action_link('index'));
			}
		}//End POST DATA
		
		//display content to view
		$this->data['tpl_file']	= 'articles/update';
		$this->data['form_submit']	=	$form_submit;
		$this->data['cats']	=	$cats;
		$this->load->view('layout/default', $this->data);
	}
	
	/*
	 * @method: list_intro
	 * @param:
	 * @return: content of page list articles introduction
	 */
	function list_intro()
	{
		$page = (isset($_GET['p']) && is_numeric($_GET['p'])) ? $_GET['p'] : 1;
		$this->db->where('type',1);
        if(isset($_GET['active'])) {
            $this->db->where('active', (int)$_GET['active']);
        }	
		if(isset($_GET['keyword'])) {    
			$keyword = $_GET['keyword'];
			$keyword = strip_tags($keyword);
			if($keyword == 'keyword')
			{
				$keyword = "";
			}
			else
			{
				$this->db->like('title', $keyword)
            		 ->or_like('description', $keyword)
            		 ->or_like('contents', $keyword)
            		 ->or_like('author', $keyword)
            		 ->or_like('source', $keyword);
			}
        }

		$this->data['articles'] 	= $this->articles_model->get_articles($page != "" ? $page : 1);
		$this->data['page'] 		= $page;

    	$conf =	array(
    		'base_url'		=> admin_url($this->router->class).'/',
    		'total_rows'	=> $this->articles_model->count_all(),
    		'per_page'		=> $this->config->item('articles', 'limit'),
    		'cur_page'		=> $page,
    	);
    	$this->pagination->initialize($conf);
    	$this->data['pagnav'] = $this->pagination->display_query_string();

		if($this->input->is_ajax_request()) {
			$this->load->view('articles/list', $this->data);
		}
		else {
			$this->data['tpl_file']	= 'articles/list_intro';
			$this->load->view('layout/default', $this->data);
		}
	}
	//End list introduction
	
	/*
	 * @method:Update article intro
	 * @param:
	 * @return:
	 * 
	 */
	function update_intro($id = null)
	{
		$form_submit	=	array();
		$article	=	array();
		$cats	=	$this->cat_articles_model->get_many_by(array('type' => 1));
		if($id)
		{
			$article	=	$this->articles_model->get_by('id',$id);
			$form_submit	=	array(
									'title' => $article->title,
									'desc'	=>	$article->desc,
									'content' => $article->content,
									'hot' => $article->hot,
									'cat_id' => $article->cat_id,
									'active' => $article->active
								);
		}
		
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			$this->form_validation->set_message('required', '%s không hợp lệ!');
    		$this->form_validation->set_rules('txt_title', 'Tiêu đề', 'required|trim|xss_clean');
    		$this->form_validation->set_rules('txt_desc', 'Mô tả', 'required|trim|xss_clean');
    		$title	=	$this->input->post('txt_title');//ascii_link
    		$title_link	=	ascii_link($title);
    		$hot	=	($this->input->post('hot') == 1 ? 1 : 0);
    		$active	=	($this->input->post('active') == 1 ? 1 : 0);
    		$cat_id	=	$this->input->post('cat');
    		
    		$data	=	array(
            	'title'	=>	$title,
            	'title_link'	=>	$title_link,
            	'content'	=>	$this->input->post('txt_content'),
            	'active'	=>	$active,
            	'cat_id'	=>	$cat_id,
    			'type'		=>	1
            );
            
            $form_submit	=	$data;
			
			$suc = false;
			//if have article then update with id
			if($article)
			{
				$data['time_update']	=	time();
				if($this->articles_model->update($article->id,$data))
				{
					$suc = true;
				}
			}//end update by id
			else 
			{
				$data['time_create']	=	time();
				if($this->articles_model->insert($data))
				{
					$suc = true;
				}
			}//end add new record
			
			//if success then redirect to list
			if($suc)
			{
				redirect(action_link('list_intro'));
			}
		}//End POST DATA
		
		//display content to view
		$this->data['tpl_file']	= 'articles/update';
		$this->data['form_submit']	=	$form_submit;
		$this->data['cats']	=	$cats;
		$this->load->view('layout/default', $this->data);
	}
	//End update article introduction
	
	/*
	 * @method: list cat
	 * @param:
	 * @return:
	 */
	function list_cat()
	{
		$this->data['tpl_file']	= 'articles/list_cat';
		$cats	=	$this->cat_articles_model->get_all();
		$this->data['cats']	=	$cats;
		$this->load->view('layout/default', $this->data);
	}//End list cat
	
	/*
	 * @method: list cat articles
	 */
	function update_cat($id = null)
	{
		$input_form	=	array();
    	$row	=	array();
    	if($id){
    		$row	=	$this->cat_articles_model->get_by('id',$id);
    		$input_form	=	$row;
    	}
    	if($_SERVER['REQUEST_METHOD'] == 'POST')
    	{
    		$name	=	$this->input->post('name');
    		$name_link	=	ascii_link($name);
    		$active		=	($this->input->post('active') == 1 ? 1 : 0);
    		$sort		=	(int)$this->input->post('sort');
    		$type		=	(int)$this->input->post('type');
    		$data	=	array(
    			'name'	=>	$name,
    			'name_link'	=>	$name_link,
    			'active'	=>	$active,
    			'sort'		=>	$sort,
    			'type'		=>	$type
    		);
    		
    		$input_form->name	=	$name;
    		$input_form->active	=	$active;
    		$input_form->sort	=	$sort;
    		$input_form->type	=	$type;
    		
    		$suc	=	false;
    		
    		//if have row then update
    		if($row)
	    	{
	    		if($this->cat_articles_model->update($row->id,$data)){
	    			$suc = true;
	    		}
	    	}//end update
	    	else 
	    	{//add new
	    		if($this->cat_articles_model->insert($data))
	    		{
	    			$suc = true;
	    		}
	    	}//end add new
	    	
	    	//if suc == true then redirect to index cat course
	    	if($suc == true)
	    	{
	    		redirect(action_link('list_cat'));
	    	}
    	}
    	
    	$this->data['input_form']	=	$input_form;
    	$this->data['tpl_file']	= 'articles/update_cat';
        $this->load->view('layout/default', $this->data);	
	}
	//update cat article
	
    function delete($articles_id = null)
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
        	$article = $this->articles_model->get_by('id',$articles_id);

            $this->articles_model->delete($articles_id);
           	unlink('uploads/news/'.$article->images_thumb);

            die('yes');
        }
    }

	function do_action()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST') {

			$id_list = $this->input->post('id');
			$action = $this->input->post('action');

			if($action == 'delete') {
				$this->delete($id_list);
			}
			elseif($action == 'pending') {
				$this->articles_model->update_many($id_list, array('status' => 'no'));
			}
			elseif($action == 'active') {
				$this->articles_model->update_many($id_list, array('status' => 'yes'));
			}

			die('yes');
		}
	}

	function change_status()
	{
		$articles_id = $this->input->post('articles_id');
		$status 	 = $this->input->post('status');

		$this->articles_model->update($articles_id, array('status' => $status));
		die('yes');
	}	

	function load_row($articles_id = null)
	{		
		$this->data['articles'] = $this->articles_model->get($articles_id);
		$this->load->view('articles/row', $this->data);
	}

	function _check_upload()
	{
		$count = 0;
		if(isset($_FILES['images'])) {
	    	$tt = count($_FILES['images']['name']);
	    	for($i = 0; $i < $tt; $i++) {
	    	    if($_FILES['images']['error'][$i] === 0) $count++;
	    	}
	    }

	    return ($count > 0) ? true : false;
	}

	/*
     * method: create thumb
     * param: path image
     * return: path/image_name
     */
	function _create_thumb($img_path = '')
	{
		$sizes = config_item('thumb_img_article');
		$this->load->helper('string');
		$pathinfo = pathinfo($img_path);
		$new_name = $pathinfo['basename'];
		$temp	=	explode('.',$pathinfo['basename']);
		$new_name	=	$temp[0].date('-his-mdy').'.'.$pathinfo['extension'];

		rename($img_path, $pathinfo['dirname'].'/'.$new_name);

        include_once (config_item('phpThumb_dir')."ThumbLib.inc.php");

        $options = array(
		    'resizeUp' 		=> true,
		    'jpegQuality'	=> 88,
        );

		
		foreach($sizes as $size)
		{
			$thumb_dir  = $pathinfo['dirname'].'/thumb_'.$size;
			create_dir($thumb_dir);

			$t_size = explode('-', $size);

		    $thumb 	= PhpThumbFactory::create($pathinfo['dirname'].'/'.$new_name, $options);

		    $thumb->adaptiveResize($t_size[0] + 5, $t_size[1] + 5);
		    $thumb->cropFromCenter($t_size[0], $t_size[1]);
		    $thumb->save($thumb_dir.'/'.$new_name, 'jpg');
		}
		return $pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name;
	}
	//End create thumb
	
	function _delete_image($img_path = '')
	{
    	$filename = basename($img_path);
        $sizes = config_item('thumb_size');

    	foreach($sizes as $size) {
    		$path = str_replace($sizes[0], $size, $img_path);
    		if(is_file($path)) unlink($path);
    	}
    	$path = str_replace('/thumb_'.$sizes[0], '', $img_path);
    	if(is_file($path)) unlink($path);
	}
	
	function deleteAll($directory, $empty = false) { 
    if(substr($directory,-1) == "/") { 
        $directory = substr($directory,0,-1); 
    } 

    if(!file_exists($directory) || !is_dir($directory)) { 
        return false; 
    } elseif(!is_readable($directory)) { 
        return false; 
    } else { 
        $directoryHandle = opendir($directory); 
        
        while ($contents = readdir($directoryHandle)) { 
            if($contents != '.' && $contents != '..') { 
                $path = $directory . "/" . $contents; 
                
                if(is_dir($path)) { 
                    deleteAll($path); 
                } else { 
                    unlink($path); 
                } 
            } 
        } 
        
        closedir($directoryHandle); 

        if($empty == false) { 
            if(!rmdir($directory)) { 
                return false; 
            } 
        } 
        
        return true; 
    } 
    
    
} 
	
	 
}

